const express = require("express");
const jwt = require("jsonwebtoken");
const { expressjwt: expressJWT } = require("express-jwt");

const app = express();

app.use(
  expressJWT({ secret: "abcdefg", algorithms: ["HS256"] }).unless({
    path: ["/login", "/refresh", /^\/html\//], // 跳过token验证
  })
);

// 配置中间件-错误捕获
app.use(function (err, req, res, next) {
  // token解析失败
  const authorization = req.headers["authorization"];
  if (!authorization) {
    return res.status(401).json({
      code: 20000,
      msg: "用户未登录",
    });
  }
  if (err.name === "UnauthorizedError") {
    return res.status(401).json({
      code: 20000,
      msg: "登录过期，请重新登录",
    });
  }
});

// 解析 JSON 格式的请求体数据 req.body
app.use(express.json());
// 托管静态文件
app.use(express.static("public")); // 访问路径 http://localhost:3000/html/index.html

// 设置路由规则
app.get("/", (req, res) => {
  res.end("Hello World");
});

// 用户列表
const userList = [{ userName: "admin", password: "123456" }];

app.post("/login", (req, res) => {
  console.log(req.body);
  let { userName, password } = req.body;
  const user = userList.find((user) => {
    return user.userName == userName;
  });

  if (!user) {
    return res.json({
      code: 20000,
      msg: "用户不存在",
    });
  }
  if (user.password !== password) {
    return res.json({
      code: 20000,
      msg: "密码错误",
    });
  }
  const userInfo = {
    userName,
  };
  const accessToken = jwt.sign(userInfo, "abcdefg", {
    expiresIn: "0.5h",
  });
  const refreshToken = jwt.sign(userInfo, "abcdefg", {
    expiresIn: "7d",
  });
  res.json({
    code: 10000,
    data: {
      userInfo,
      accessToken,
      refreshToken,
    },
  });
});

// 获取用户信息
app.post("/getUserInfo", (req, res) => {
  res.json({
    code: 10000,
    data: req.auth,
  });
});

// 刷新Token
app.get("/refresh", (req, res) => {
  const token = req.query.token;
  let userName = "";
  try {
    const userInfo = jwt.verify(token, "abcdefg");
    userName = userInfo.userName;
  } catch (error) {
    return res.status(401).json({
      code: 20000,
      msg: "token 失效，请重新登录",
    });
  }
  const userInfo = {
    userName,
  };
  const accessToken = jwt.sign(userInfo, "abcdefg", {
    expiresIn: "0.5h",
  });
  const refreshToken = jwt.sign(userInfo, "abcdefg", {
    expiresIn: "7d",
  });
  res.json({
    code: 10000,
    data: {
      accessToken,
      refreshToken,
    },
  });
});

app.listen(3000, () => {
  console.log("服务器已启动：3000");
});
